import { ModelRef } from "vue"
import { Customer } from '@/api/customer/type'
import { useRole } from '@/views/system/role.hook'
import { post, ResponseCode } from '@/api/http'
import { CUSTOMER_CREATE, CUSTOMER_UPDATE } from '@/api/customer'
import { Form, Message } from '@arco-design/web-vue'
import type { UserState } from '@/store/types'
import useUserStore from '@/store/modules/user'
import { useUser } from '@/views/system/user.hook'

type AddClientEmits = (evt: "doRefresh") => void

type AddClientModel = {
  visible: ModelRef<boolean | undefined, string>,
  customer: ModelRef<Customer | undefined, string>
}

type AddClientForm = {
  accountManager: string,
  amountAlreadyAdvanced: number,
  customerAvailableAmount: number,
  customerName: string,
  customerTiktokId: string,
  policyPoints: number,
  remarks: string,
  tiktokAvailableAmount: number,
}

const initAddClientForm = {
  accountManager: '',
  amountAlreadyAdvanced: 0,
  customerAvailableAmount: 0,
  customerName: '',
  customerTiktokId: '',
  policyPoints: 0,
  remarks: '',
  tiktokAvailableAmount: 0,
}

export const useAddClient = (props: any, emits: AddClientEmits, models: AddClientModel) => {
  const { roles, getRoles } = useRole()
  const { info, isManager } = useUserStore()
  const { users, getUserList } = useUser()

  const modalProps = reactive({
    loading: false,
  })

  const form = ref<AddClientForm>(initAddClientForm)
  const formRef = ref<typeof Form>()
  const managers = ref<UserState[]>([])

  watch(models.visible, (bool) => {
    if (bool) {
      if (models.customer.value?.id) {
        form.value = models.customer.value
        form.value.policyPoints = Math.round(models.customer.value.policyPoints * 100)
      }

      if (isManager) {
        managers.value = [info!]
        form.value.accountManager = info!.userId.toString()
      }

    } else {
      form.value = initAddClientForm
      if (models.customer.value?.id) {
        models.customer.value = undefined
      }
    }
  })

  const init = async () => {
    if (!roles.value.length) {
      getRoles()
    }
    if (isManager) {
      if (!users.value.length) {
        const { success, data } = await getUserList()
        if (success) {
          return managers.value = users.value = data
        }
      }

      managers.value = users.value
    }
  }

  const submit = async (done: (closed: boolean) => void) => {
    modalProps.loading = true
    const err = await formRef.value?.validate()
    if (err) return (modalProps.loading = false)
    if (models.customer.value?.id) {
      const { code, message } = await post({
        url: CUSTOMER_UPDATE,
        data: {
          id: models.customer.value.id,
          ...form,
          policyPoints: form.value!.policyPoints / 100,
        },
      }).catch((err) => {
        return err
      })
      modalProps.loading = false
      if (code === ResponseCode.SUCCESS) {
        Message.success(message)
        emits('doRefresh')
        return done(true)
      } else {
        Message.warning(message)
      }
    } else {
      const { code, message } = await post({
        url: CUSTOMER_CREATE,
        data: {
          ...form.value,
          policyPoints: form.value!.policyPoints / 100,
        },
      }).catch((err) => {
        return err
      })
      modalProps.loading = false
      if (code === ResponseCode.SUCCESS) {
        Message.success(message)
        emits('doRefresh')
        return done(true)
      } else {
        Message.warning(message)
      }
    }
  }

  onMounted(init)

  return {
    form,
    submit,
    formRef,
    managers,
    modalProps,
  }
}
